/*
 * @Author: intellectual-seeker 3336339701@qq.com
 * @Date: 2025-11-15 20:06:49
 * @LastEditors: intellectual-seeker 3336339701@qq.com
 * @LastEditTime: 2025-11-17 14:56:41
 * @FilePath: /code/lesson34/udp_echo_server/UdpServer.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once
#include <sys/types.h>
#include <sys/socket.h>
#include <string>
#include "Log.hpp"
#include <strings.h>
#include <cstring>
#include "InetAddr.hpp"

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    USAGE_ERROR
};

static int defualt_fd = -1;

class UdpServer
{
public:
    UdpServer(uint16_t port)
        :_sockfd(defualt_fd), _port(port), _isrunning(false)
    {}

    void InitServer()
    {
        //1. 创建sock_fd
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            //打印到屏幕
            LOG(FATAL, "sock error, %s, %d", strerror(errno), errno);
            exit(SOCKET_ERROR);
        }
        LOG(INFO, "socket create success, sockfd: %d", _sockfd);

        //2. 填充struct sockaddr_in
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);//将主机序转为网络序

        //local.sin_addr.s_addr = inet_addr(_ip);//绑定确定的网络IP

        local.sin_addr.s_addr = INADDR_ANY;//表示绑定到所有可用的本地IP地址
        

        //3. 绑定sockfd 与 struct sockaddr_in
        int n = bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
        if(n < 0)
        {
            LOG(FATAL, "bind error, %s, %d", strerror(errno), errno);
            exit(BIND_ERROR);
        }
        LOG(INFO, "socket bind success");

    }

    void Start()
    {
        //服务器、先收后发
        _isrunning = true;
        while(true)
        {
            char buf[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);

            ssize_t n = recvfrom(_sockfd, buf, sizeof(buf) - 1, 0, (struct sockaddr*)&peer, &len);
            if(n > 0)
            {
                buf[n] = 0;
                InetAddr addr(peer);
                LOG(INFO, "get message from [%s:%d] %s", addr.Ip(), addr.Port(), buf);
                sendto(_sockfd, buf, strlen(buf), 0, (struct sockaddr*)&peer, len);
            }
        }

        _isrunning = false;
    }

    ~UdpServer()
    {}

private:
    int _sockfd;
    uint16_t _port;
    string _ip;
    bool _isrunning;
};